import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/LoadToast.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/SetPower.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/ShowToast.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/requestUrl.dart';
import 'package:shared_preferences/shared_preferences.dart';

/**
 * Creat For 11643
 * CreatTime 2022/12/28
 * Description:
 */
class LingYong extends StatefulWidget {
    LingYong({Key? key,required this.TypeList,required this.AssetUseID}) : super(key: key);
    //领用的物资类别集合
  var TypeList;
  ///领用单ID
    var AssetUseID;
  @override
  _LingYongState createState() => _LingYongState();
}

class _LingYongState extends State<LingYong> {
  //原生主动向flutter发送数据通道
  static const channel = const BasicMessageChannel(
      'com.flutter.BasicMessageChannel', StandardMessageCodec());
  ///定义一个通道,flutter调用原生方法
  static const platform = const MethodChannel('com.RfidRead.rfidread');
  //是否读取中
  bool IsReading = false;
  //手持机是否初始化成功
  var IsInit = "false";
  String Token="";
  List EPCList=[];
  ///需要领用的物资集合
  List AssetUseTypes = [];
  ///读取的物资列表
  List GoodsList = [];
  ///一维数组（只存放物资类别ID）
  List GoodsTypeList = [];
  ///页面加载
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero,() async {
      // 获取本地token
      final SharedPreferences sharedPreferences =
      await SharedPreferences.getInstance();
      // 获取本地token
      Token = sharedPreferences.getString('Token')!;
      AssetUseTypes = json.decode(widget.TypeList);
      AssetUseTypes.forEach((element) {
        GoodsTypeList.add(element['AssetCategoryID']);
      });
      InitRfid();
    });
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text("领用", style: TextStyle(fontSize: 15)),
            elevation: 0,
          actions: [
            IconButton(onPressed: (){
              // 设置功率
              Navigator.push(context, MaterialPageRoute(builder: (context)=>SetPower(SetPowerType: "LingYongPower",)));
            }, icon: Icon(Icons.settings,color: Colors.white,))
          ],
        ),
        body: Container(
          padding: EdgeInsets.only(left: 15,right: 15),
          child: Column(
            children: [
              Container(
                height: 100,
                child: ListView.builder(
                  itemBuilder: (context,index){
                    return Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("物资类别:${AssetUseTypes[index]['AssetCategoryName']}"),
                        Text("领用进展:${AssetUseTypes[index]['UseOK']}/${AssetUseTypes[index]['UseCount']}",style: TextStyle(
                            color: AssetUseTypes[index]['UseOK'] ==
                                AssetUseTypes[index]['UseCount']
                                ? Colors.green
                                : Colors.red)),
                      ],
                    );
                  },itemCount:AssetUseTypes.length,),
              ),
              Container(
                alignment: Alignment.topLeft,
                child: Text("领用列表",style: TextStyle(fontSize: 17,fontWeight: FontWeight.w600),),
              ),
              Expanded(
                child: ListView.builder(
                  itemBuilder: (context,index){
                  return Container(
                    decoration: BoxDecoration(
                      border: Border(bottom: BorderSide(width: 0.5,color: Colors.black26))
                    ),
                    child: CheckboxListTile(
                      title: Text("物资类别:${GoodsList[index]['AssetCategoryIDName']}"),
                      subtitle:Text("物资编码:${GoodsList[index]['RFIDCode']}"),
                      onChanged: (bool? value) {
                        setState(() {
                          GoodsList[index]['IsCheck'] = value;
                        });
                    }, value: GoodsList[index]['IsCheck'],
                    ),
                  );
                },itemCount: GoodsList.length,),
              ),
              ///底部按钮
              Container(
                height: 50,
                width: MediaQuery.of(context).size.width - 30,
                child: GridView(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount:3,
                  ),
                  children: [
                    GestureDetector(
                      child: Container(
                        alignment: Alignment.topCenter,
                        child:   Column(
                          children: [
                            Icon(Icons.wifi,color:IsReading?Colors.red:Colors.black38),
                            Text(IsReading?"停止读取":"开始读取",style: TextStyle(fontSize: 13,color: IsReading?Colors.red:Colors.black38))
                          ],
                        ),
                      ),
                      onTap: (){
                        if(IsReading){
                          //停止读卡
                          StopRead();
                        }else{
                          //读卡
                          ReadRfid();
                        }

                      },
                    ),
                    GestureDetector(
                      child:Container(
                        alignment: Alignment.topCenter,
                        child:   Column(
                          children: [
                            Icon(Icons.delete,color: Colors.orange),
                            Text("清空数据",style: TextStyle(fontSize: 13,color: Colors.orange))
                          ],
                        ),
                      ),
                      onTap: (){
                        if(IsReading){
                          ShowToast().MyToast("请先停止读卡");
                          return;
                        }
                        //  情况数据
                        showAlertDialog();
                      },
                    ),
                    GestureDetector(
                      child: Container(
                        alignment: Alignment.topCenter,
                        child:   Column(
                          children: [
                            Icon(Icons.cloud_upload,color: Colors.green),
                            Text("上传数据",style: TextStyle(fontSize: 13,color: Colors.green))
                          ],
                        ),
                      ),
                      onTap: (){
                        if(IsReading){
                          ShowToast().MyToast("请先停止读卡");
                          return;
                        }
                        //上传
                        UploadLingYong();
                      },
                    )
                  ],
                ),
              ),
              Container(
                height: 10,
              ),
            ],
          ),
        ) // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
  //  初始化rfid
  Future<void> InitRfid() async {
    // 加载框
    LoadToast().LoadingToast("初始化中...", context);
    var isinit = await platform.invokeMethod("InitRfid");
    //取出本地保存的功率
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    IsInit = isinit;
    if (isinit == "true") {
      print("初始化成功");
      if (await sharedPreferences.getInt("LingYongPower") != null) {
        var Power = await sharedPreferences.getInt("LingYongPower");
        //  设置功率
        bool IsSet = await platform.invokeMethod('SetPower', Power);
        if (IsSet) {
          new ShowToast().MyToast("初始化成功");
        }
      } else {
        //  用系统给用户默认的功率10
        //  设置功率
        bool IsSet = await platform.invokeMethod('SetPower', 20);
        if (IsSet) {
          new ShowToast().MyToast("初始化成功");
          //  保存本地
          await sharedPreferences.setInt("LingYongPower", 20);
        }
      }
    } else {
      ShowToast().MyToast("初始化失败，请重新进入此页面!");
    }
    // GetLocationList();
    IniListenNative();
    OpenScan();
    print("初始化设备结果$isinit");
  }

  // 读取
  ReadRfid() async   {
    //  开始读取
    IsReading = true;
    setState(() {

    });
    platform.invokeMethod('ReadRfid');
  }
  //单次读取
  ReadRfidOne() async {
    // var data={
    //   "Offset":_Offset,
    //   "Len":_Len
    // };
    platform.invokeMethod('ReadRFIDOne');
  }
  // 停止读卡
  void StopRead()   {
    IsReading = false;
    setState(() {
    });
    platform.invokeMethod('StopReadRfid');
  }
  // 销毁rfid
  DisposeRFID()  {
    IsInit = "false";
    platform.invokeMethod('onDestroy');
  }
  //打开扫描
  OpenScan()async{
    platform.invokeMethod('InitScan');
  }
  //销毁扫描
  DisScan(){
    platform.invokeMethod('DestoryScan');

  }
  //  注册监听原生发送的数据
  IniListenNative() {
    LoadToast().CloseLoading();
    var value;
    channel.setMessageHandler((message) async {
      print("BluDemo已接受到原生主动发出的数据$message");
      value = json.decode(message.toString());
      if(value['Type']=="Scan"){
        if(!EPCList.contains(value['ScanData'])){
          EPCList.add(value['ScanData']);
          ///调用原生请求接口、
          var data = {
            "ID":value['ScanData'],
            "Url":ApiUrl+"/api/AppAssetStock/GetModel",
            "Token":Token
          };
          platform.invokeMethod('GetRfidMessagePost',data);
        }
      }else if(value['Type']=="onKeyDown"){
        //  监听摁键摁下
        ReadRfid();
      }else if(value['Type']=="onKeyUp"){
        //摁键抬起
        StopRead();
      }else if(value['Type'] == "Request"){
        if(value['Data']!=""||value['Data']!=null){
          if(GoodsTypeList.contains(value['Data']['AssetCategoryID']) ){
        //如果匹配到了物资类别
            log("找到了相同类别");
            value['Data']['IsCheck'] = false;
            GoodsList.add(value['Data']);
          }
        }
      }
      else{
        if(value['Epc']!=""){
          if(!EPCList.contains(value['Epc'])){
            EPCList.add(value['Epc']);
            ///调用原生请求接口、
            var data = {
              "ID":value['Epc'],
              "Url":ApiUrl+"/api/AppAssetStock/GetModel",
              "Token":Token
            };
            platform.invokeMethod('GetRfidMessagePost',data);
          }
          setState(() {
          });
        }
      }
      setState(() {
      });
    });
    setState(() {
    });
  }
  Clear(){
    EPCList.clear();
    GoodsList.clear();
    setState(() {
    });
  }

//上传领用数据
  UploadLingYong() async {
    var ResponseData;
    var AssetCodeOrRFIDCode=[];

    //构造上传的数据
    GoodsList.forEach((item) {
      if(item['IsCheck']){
        AssetCodeOrRFIDCode.add(item['AssetCode']);
      }
    });
    print("上传数据列表i$AssetCodeOrRFIDCode");
    if(AssetCodeOrRFIDCode.isEmpty){
      ShowToast().MyToast('请勾选领用的物资！');
      return;
    }
    ResponseData = await new requestUrl().CommenRequest(
        '/api/AppAssetUse/AddInfo', 'post',
        {
          "AssetUseID":widget.AssetUseID,
          "AssetCodeOrRFIDCode":AssetCodeOrRFIDCode.join(",")
        }, "上传中...", context, true,"application/x-www-form-urlencoded");
    if (ResponseData['code'] == 0) {
      ShowToast().MyToast('上传成功！');
      Navigator.pop(context,"reflash");
    } else {
      ShowToast().MyToast(ResponseData['msg']);
    }
  }
  ///弹窗
  void showAlertDialog() {
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: new Text('警告！'),
            //可滑动
            content: Text("确定要清空数据吗？"),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                  Clear();
                },
              ),
              new FlatButton(
                child: new Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }
}